<script lang="ts" setup>
import {onBeforeUnmount, onMounted, ref} from "vue";
import {getUserInfo} from "@/utils/system";
import boy1 from "@/asserts/webChat/boy1.svg";
import girl1 from "@/asserts/webChat/girl1.svg";
import {useWebSocketStore} from "@/stores/webSocketStore";
import {getAllUserList, getOnlineUserByWebSocket} from "@/api/system/sysUser";
import {message} from "@/utils/ElmessasgeUtils";
import {formatCurrentTime, generateSimpleMonthWeek} from "@/utils/dateUtils";
import type {WebChatMessageShow} from "@/type/admin/webChat";
import {getWebChatUserBucketNameByUserId, selectByBothUser} from "@/api/admin/webChat";
import {getFileType} from "@/views/documentManager/components/ts/fileTypeManager";
import {FileUploader} from "@/views/documentManager/components/ts/BigFileUpload";
import type {WebSocketDataBody} from "@/type/common/websocketType";
import {WEBSOCKET_MESSAGE_TYPE} from "@/enum/admin/WebSocketDataTypeEnum";
import {downloadBucketFile} from "@/api/documentManage/minioManager2";

// 表情列表
const emojiList = [
  '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣',
  '😊', '😇', '🙂', '😉', '😌', '😍', '🥰', '😘',
  '😗', '😙', '😚', '😋', '😛', '😜', '🤪', '😝',
  '🤑', '🤗', '🤭', '🤫', '🤔', '🤐', '🤨', '😐',
  '😑', '😶', '😏', '😒', '🙄', '😬', '😮‍💨', '🤥',
  '😌', '😔', '😪', '🤤', '😴', '😷', '🤒', '🤕'
];

// 文件类型图标映射
const fileTypeIcons = {
  docx: '📄',
  xlsx: '📊',
  pptx: '📑',
  pdf: '📄',
  text: '📝',
  html: '🌐',
  image: '🖼️',
  audio: '🎵',
  video: '🎬',
  sql: '🗄️',
  zip: '📦',
  default: '📎'
};

const messageList = ref<WebChatMessageShow[]>([])
const inputMessage = ref('')
const showEmojiPanel = ref(false)
const fileInput = ref<HTMLInputElement | null>(null)
const imageInput = ref<HTMLInputElement | null>(null)

const webChatBucketName = ref<string>("")

// 选中的聊天用户
const selectedUser = ref<webChatUserListType | null>(null)

// 在应用启动时初始化 WebSocket
const websocketStore = useWebSocketStore()

// 聊天用户列表
const webChatUserList = ref<webChatUserListType[]>([])

const selfUserId = getUserInfo().userId

// 处理用户选择
const handleUserSelect = async (user: webChatUserListType) => {
  // 检查是否点击自己（理论上不会发生，因为列表中已过滤掉自己）
  if (user.userId === selfUserId) {
    message("不能与自己聊天", "warning");
    return;
  }

  // 更新选中用户
  selectedUser.value = user;

  // 刷新消息列表
  await updateWebChatList(user.userId);
}

// 处理接收到的消息
const handleReceivedMessage = (payload: any) => {
  console.log("收到后台Websocket消息", payload)
  let myUserId = getUserInfo().userId
  let fromUserId = payload.fromUserId
  let toUserId = payload.toUserId
  let selectedUserId = selectedUser.value?.userId

  if (toUserId == myUserId && fromUserId == selectedUserId) {
    // 根据消息类型处理不同的消息
    const messageToAdd = {
      msg: payload.msg,
      fromUserId: payload.fromUserId,
      fromUserName: payload.fromUserName,
      fromNickName: payload.fromNickName,
      avatar: boy1,
      createTime: payload.createTime,
      type: payload.type || WEBSOCKET_MESSAGE_TYPE.WEB_CHAT_TEXT || WEBSOCKET_MESSAGE_TYPE.WEB_CHAT_EMOJI,
      data: payload.data
    };

    messageList.value.push(messageToAdd);
    scrollToTail()
  }

}


// 发送消息到WebSocket 服务器
function sendMessageToWSServer(message: WebSocketDataBody) {
  websocketStore.sendMessage(message)

  // 添加发送的消息到列表（带头像与昵称）
  const messageToAdd = {
    msg: message.msg,
    fromUserId: message.fromUserId,
    fromUserName: message.fromUserName,
    fromNickName: message.fromNickName,
    avatar: girl1,
    createTime: message.createTime,
    type: message.type || WEBSOCKET_MESSAGE_TYPE.WEB_CHAT_TEXT,
    data: message.data
  };

  messageList.value.push(messageToAdd);

  inputMessage.value = '';
  scrollToTail()
}

// 处理发送文本消息
const handleSendMessage = () => {
  if (!selectedUser.value) {
    message("请先选择聊天对象", "warning");
    return;
  }
  
  if (inputMessage.value.trim()) {
    let sendMsg: WebSocketDataBody = {
      type: WEBSOCKET_MESSAGE_TYPE.WEB_CHAT_TEXT,
      msg: inputMessage.value,
      fromUserId: getUserInfo().userId,
      fromUserName: getUserInfo().username,
      fromNickName: getUserInfo().nickname,
      createTime: formatCurrentTime(),
      toUserId: selectedUser.value.userId
    }
    sendMessageToWSServer(sendMsg);
  }
};

// 处理发送表情
const handleSendEmoji = (emoji: string) => {
  if (!selectedUser.value) {
    message("请先选择聊天对象", "warning");
    return;
  }
  
  let sendMsg: WebSocketDataBody = {
    type: WEBSOCKET_MESSAGE_TYPE.WEB_CHAT_EMOJI,
    msg: emoji,
    fromUserId: getUserInfo().userId,
    fromUserName: getUserInfo().username,
    fromNickName: getUserInfo().nickname,
    createTime: formatCurrentTime(),
    data: null,
    toUserId: selectedUser.value.userId
  };
  sendMessageToWSServer(sendMsg);
  showEmojiPanel.value = false;
};

// 处理文件按钮点击
const handleFileButtonClick = () => {
  if (!selectedUser.value) {
    message("请先选择聊天对象", "warning");
    return;
  }
  
  if (fileInput.value) {
    fileInput.value.click();
  }
};

// 处理图片按钮点击
const handleImageButtonClick = () => {
  if (!selectedUser.value) {
    message("请先选择聊天对象", "warning");
    return;
  }
  
  if (imageInput.value) {
    imageInput.value.click();
  }
};

// 处理发送文件
const handleSendFile = (event: Event) => {
  if (!selectedUser.value) {
    message("请先选择聊天对象", "warning");
    return;
  }
  
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  let imageFlag = false;

  if (!file) return;

  // 检查是否为图片文件
  if (file.type.startsWith('image/')) {
    imageFlag = true;
  }

  // 使用FileUploader上传文件
  const uploader = new FileUploader(
      file,
      webChatBucketName.value,
      generateSimpleMonthWeek() + "/",
      (progress) => {
        // 可以在这里添加上传进度提示
        console.log(`文件 ${file.name} 上传进度: ${progress.percentage}%`);
      },
      (mergeRes: any) => {
        console.log("合并分片成功返回结果： ", mergeRes);
        // 上传成功，获取文件类型和相关信息
        const fileType = getFileType(file.name);
        const fileInfo = {
          name: mergeRes.fileName,
          size: formatFileSize(file.size),
          type: fileType,
          url: mergeRes.url, // 使用服务器返回的URL
          icon: getFileIcon(fileType),
          path: mergeRes.path,
          bucket: mergeRes.bucketName,
        };

        // 发送文件消息
        let sendMsg: WebSocketDataBody = {
          type: imageFlag ? WEBSOCKET_MESSAGE_TYPE.WEB_CHAT_IMAGE : WEBSOCKET_MESSAGE_TYPE.WEB_CHAT_FILE,
          msg: imageFlag ? `发送了图片: ${file.name}` : `发送了文件: ${file.name}`,
          fromUserId: getUserInfo().userId,
          fromUserName: getUserInfo().username,
          fromNickName: getUserInfo().nickname,
          createTime: formatCurrentTime(),
          data: fileInfo,
          toUserId: selectedUser.value.userId
        };

        sendMessageToWSServer(sendMsg);
        message(`文件发送成功: ${file.name}`, 'success');

        // 重置文件输入
        if (fileInput.value) {
          fileInput.value.value = '';
        }
      },
      (error) => {
        message('文件发送失败', 'error');
        console.error('文件发送失败:', error);

        // 重置文件输入
        if (fileInput.value) {
          fileInput.value.value = '';
        }
      }
  );

  // 开始上传
  uploader.startUpload();
};

// 格式化文件大小
function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 获取文件图标
function getFileIcon(fileType: string): string {
  return fileTypeIcons[fileType as keyof typeof fileTypeIcons] || fileTypeIcons.default;
}

// 处理预览文件
const handlePreviewFile = (fileInfo: any) => {
  if (fileInfo.type === 'image') {
    // 图片可以直接在浏览器中预览
    const imageWindow = window.open('', '_blank');
    if (imageWindow) {
      imageWindow.document.write(`<img src="${fileInfo.url}" style="max-width: 100%; max-height: 100%;">`);
      imageWindow.document.title = fileInfo.name;
    }
  } else {
    // 其他类型的文件提示下载或使用相应的应用打开
    message('准备下载文件：' + fileInfo.bucket + ' : ' + fileInfo.path + fileInfo.name, 'info');
    downloadItem(fileInfo.bucket, fileInfo.path + fileInfo.name)

  }
};

// 点击 下载按钮
function downloadItem(bucketName: string, fullPath: string) {

  downloadBucketFile(bucketName, fullPath).then(res => {
    console.log(res)
  })


}

// 处理预览图片（专门用于消息列表中的图片预览）
const handlePreviewImage = (imageInfo: any) => {
  const imageWindow = window.open('', '_blank');
  if (imageWindow) {
    imageWindow.document.write(`<img src="${imageInfo.url}" style="max-width: 100%; max-height: 100%;">`);
    imageWindow.document.title = imageInfo.name;
  }
};

// 切换表情面板显示状态
const toggleEmojiPanel = () => {
  showEmojiPanel.value = !showEmojiPanel.value;
}

// 处理回车键发送
const handleKeyPress = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault();
    handleSendMessage();
  }
}


// 解析 content 字段
const parseContent = (content: string): any | null => {
  try {
    return JSON.parse(content)
  } catch (err) {
    console.error('解析消息内容失败:', err)
    return null
  }
}

// 解析整个消息数组
const parseMessages = (messages: any): any[] => {
  return messages.map((message: any) => (
      parseContent(message.content)
  ))
}

// 从后端获取，刷新消息列表
async function updateWebChatList(_receiver: string = '1') {
  let res = await selectByBothUser({receiver: _receiver, sender: getUserInfo().userId})
  if (res.data.code === 200) {
    let data = res.data.data

    const parsedData: any = parseMessages(data)
    console.log(parsedData)
    messageList.value = parsedData

    scrollToTail()
  } else {
    message("获取消息列表失败", "error")
  }

}

// 点击外部关闭表情面板
const handleClickOutside = (event: MouseEvent) => {
  const emojiPanel = document.getElementById('emoji-panel');
  const emojiButton = document.getElementById('emoji-button');
  if (emojiPanel && emojiButton &&
      !emojiPanel.contains(event.target as Node) &&
      !emojiButton.contains(event.target as Node)) {
    showEmojiPanel.value = false;
  }
};

// 自动滚动到底部（平滑滚动）
function scrollToTail() {
  setTimeout(() => {
    const messageContainer = document.getElementById('message-container');
    if (messageContainer) {
      // 使用scrollTo方法并设置behavior为smooth实现平滑滚动
      messageContainer.scrollTo({
        top: messageContainer.scrollHeight,
        behavior: 'smooth'
      });
    }
  }, 100);
}

async function getUserBucketName() {
  let res: any = await getWebChatUserBucketNameByUserId()

  if (res.data.code === 200) {
    webChatBucketName.value = res.data.data.bucketName
  } else {
    message("获取用户相关bucketName 失败", "error");
  }

}

// 获取在新用户列表
async function getOnlineUserList() {
  let _onlineUserList: any[] = []

  let res: any = await getOnlineUserByWebSocket()

  if (res.data.code === 200) {
    _onlineUserList = res.data.data
  } else {
    message('获取用户将列表失败', 'error')
  }
  return _onlineUserList

}

async function getAllSystemUserList() {
  let _allSystemUserList: any[] = []
  let res: any = await getAllUserList()
  if (res.data.code === 200) {
    _allSystemUserList = res.data.data
  } else {
    message("获取用户列表失败", "error");
  }
  return _allSystemUserList
}

// 更新webChat 用户列表
async function updateWebChatUserList() {
  webChatUserList.value = []
  let allUser: any[] = await getAllSystemUserList()
  let onlineUsers: any[] = await getOnlineUserList()

  // 提取在线用户的 userId 集合，便于快速查找
  const onlineUserIds = new Set(onlineUsers.map(user => user.userId));

  // 转换并添加在线状态，过滤掉自己
  webChatUserList.value = allUser
      .filter(user => user.userId !== selfUserId) // 不显示自己
      .map(user => ({
        nickname: user.nickname,
        username: user.username,
        userId: user.userId,
        onlineStatus: onlineUserIds.has(user.userId) ? 1 : 0
      })).sort((a, b) => b.onlineStatus - a.onlineStatus);

  // 默认选择第一个用户
  if (webChatUserList.value.length > 0 && !selectedUser.value) {
    await handleUserSelect(webChatUserList.value[0]);
  }
}

interface webChatUserListType {
  nickname: string,
  username: string,
  userId: string,
  onlineStatus: number
}

onMounted(async () => {
  await updateWebChatUserList()

  await getUserBucketName()
  // 初始时不自动加载消息

  // 注册WebSocket 消息处理
  websocketStore.onMessage(WEBSOCKET_MESSAGE_TYPE.WEB_CHAT_EMOJI, handleReceivedMessage)
  websocketStore.onMessage(WEBSOCKET_MESSAGE_TYPE.WEB_CHAT_TEXT, handleReceivedMessage)
  websocketStore.onMessage(WEBSOCKET_MESSAGE_TYPE.WEB_CHAT_FILE, handleReceivedMessage)
  websocketStore.onMessage(WEBSOCKET_MESSAGE_TYPE.WEB_CHAT_IMAGE, handleReceivedMessage)

  websocketStore.onMessage(WEBSOCKET_MESSAGE_TYPE.USER_ONLINE, updateWebChatUserList) // 自动更新上线列表
  websocketStore.onMessage(WEBSOCKET_MESSAGE_TYPE.USER_OFFLINE, updateWebChatUserList) // 自动更新上线列表
  document.addEventListener('click', handleClickOutside);
  scrollToTail()
})

// 解除挂载前 关闭连接
onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside);

  webChatUserList.value = []

})
</script>

<template>
  <div class="websocket-client-container">
    <!-- 标题和连接控制区域 -->
    <div class="client-layout">
      <!-- 左侧在线用户列表 -->
      <aside class="sidebar">
        <div class="sidebar-header">用户列表（{{ webChatUserList.length }}）</div>
        <div id="online-user-list" class="user-list">
          <div v-for="u in webChatUserList" :key="u.userId"
               :class="{ self: u.userId === selfUserId, offline: u.onlineStatus === 0, active: selectedUser && u.userId === selectedUser.userId }"
               class="user-item"
               @click="handleUserSelect(u)">
            <img alt="avatar" class="user-avatar" src="@/asserts/girl.jpg"/>
            <div class="user-name">{{ u.nickname }}</div>
            <div v-if="u.onlineStatus === 0" class="offline-badge">离线</div>
          </div>
        </div>
      </aside>

      <!-- 右侧聊天区域 -->
      <section class="chat-area">
        <!-- 消息显示区域 -->
        <div class="message-display-container">
          <!-- 聊天标题 -->
          <div class="chat-header">
            {{ selectedUser ? selectedUser.nickname : '选择用户开始聊天' }}
          </div>
          <div id="message-container" class="message-container">
            <div v-if="messageList.length === 0" class="empty-message">
              暂无消息
            </div>
            <div
                v-for="(message, index) in messageList"
                :key="index"
                :class="['message-item', message.fromUserId == getUserInfo().userId ? 'sent' : 'receive']"
            >
              <img :src="message.fromUserId == getUserInfo().userId ? boy1 : girl1" alt="avatar" class="avatar"/>
              <div class="bubble">
                <div class="name">
                  {{ message.fromUserId == getUserInfo().userId ? '我' : (message.fromNickName || '未知用户') }}
                </div>
                <!-- 文本消息 -->
                <div v-if="!message.type || message.type == WEBSOCKET_MESSAGE_TYPE.WEB_CHAT_TEXT"
                     class="message-content">
                  {{ message.msg }}
                </div>
                <!-- 表情消息 -->
                <div v-else-if="message.type == WEBSOCKET_MESSAGE_TYPE.WEB_CHAT_EMOJI" class="emoji-content">
                  {{ message.msg }}
                </div>
                <!-- 图片消息 -->
                <div v-else-if="message.type === WEBSOCKET_MESSAGE_TYPE.WEB_CHAT_IMAGE && message.data"
                     class="image-content"
                     @click="handlePreviewImage(message.data)">
                  <img
                      :alt="message.data.name"
                      :src="message.data.url"
                      class="preview-image"
                      loading="lazy"
                      style="max-width: 200px; max-height: 150px; cursor: pointer; border-radius: 4px;"
                  />
                  <div class="image-name">{{ message.data.name }}</div>
                </div>
                <!-- 文件消息 -->
                <div v-else-if="message.type === WEBSOCKET_MESSAGE_TYPE.WEB_CHAT_FILE && message.data"
                     class="file-content"
                     @click="handlePreviewFile(message.data)">
                  <span class="file-icon">{{ message.data.icon }}</span>
                  <div class="file-info">
                    <div class="file-name">{{ message.data.name }}</div>
                    <div class="file-size">{{ message.data.size }}</div>
                  </div>
                  <span class="file-action">📥</span>
                </div>
                <div class="message-time">{{ message.createTime }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 消息输入区域 -->
        <div class="input-section-wrapper">
          <!-- 输入工具栏 -->
          <div class="input-toolbar">
            <button id="image-button" class="tool-button" @click="handleImageButtonClick">
              🖼️
            </button>
            <button id="file-button" class="tool-button" @click="handleFileButtonClick">
              📎
            </button>
            <button id="emoji-button" class="tool-button" @click.stop="toggleEmojiPanel">
              😊
            </button>
            <input
                ref="fileInput"
                style="display: none"
                type="file"
                @change="handleSendFile"
            />
            <input
                ref="imageInput"
                accept="image/*"
                style="display: none"
                type="file"
                @change="handleSendFile"
            />
          </div>

          <!-- 表情面板 -->
          <div v-if="showEmojiPanel" id="emoji-panel" class="emoji-panel">
            <div
                v-for="(emoji, index) in emojiList"
                :key="index"
                class="emoji-item"
                @click="handleSendEmoji(emoji)"
            >
              {{ emoji }}
            </div>
          </div>

          <!-- 输入框和发送按钮 -->
          <div class="input-section">
            <textarea
                v-model="inputMessage"
                class="message-input"
                placeholder="请输入消息内容...\n(按Enter发送，Shift+Enter换行)"
                rows="3"
                @keydown="handleKeyPress"
            ></textarea>
            <button
                class="send-btn"
                @click="handleSendMessage"
            >
              发送消息
            </button>
          </div>
        </div>
      </section>
    </div>
  </div>
</template>

<style scoped>
.websocket-client-container {
  width: 100%;
  max-width: 1234px;
  margin: 20px auto 10px auto;
  padding: 20px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.client-layout {
  display: flex;
  gap: 12px;
}

.sidebar {
  width: 220px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  background: #fff;
}

.sidebar-header {
  padding: 10px 12px;
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
  color: #333;
}

.user-list {
  max-height: 400px;
  overflow-y: auto;
}

.user-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 10px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.user-item:hover:not(.self) {
  background-color: #f5f5f5;
}

.user-item.active {
  background-color: #e6f7ff;
}

.user-item.active .user-name {
  color: #1890ff;
}

.user-item.self .user-name {
  color: #1890ff;
}

.user-avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
}

.user-name {
  font-size: 13px;
  color: #333;
}

/* 离线用户样式 */
.user-item.offline {
  opacity: 0.6;
}

.user-item.offline .user-name {
  color: #999;
}

/* 离线标签 */
.offline-badge {
  font-size: 11px;
  color: #999;
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 10px;
  margin-left: auto;
}

.chat-area {
  flex: 1;
}

.connect-btn, .disconnect-btn, .send-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.connect-btn {
  background-color: #1890ff;
  color: white;
}

.connect-btn:hover:not(:disabled) {
  background-color: #40a9ff;
}

.connect-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.disconnect-btn {
  background-color: #f5222d;
  color: white;
}

.disconnect-btn:hover:not(:disabled) {
  background-color: #ff4d4f;
}

.disconnect-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.message-display-container {
  height: 65vh;
  margin-bottom: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
}

.chat-header {
  padding: 10px 15px;
  background-color: #fafafa;
  border-bottom: 1px solid #e8e8e8;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.message-container {
  height: calc(100% - 42px);
  padding: 15px;
  overflow-y: auto;
  background-color: #fafafa;
}

.empty-message {
  text-align: center;
  color: #999;
  margin-top: 150px;
  font-size: 14px;
}

/* 重置原有 message-item 的背景，改为行容器 */
.message-item {
  display: flex;
  gap: 8px;
  align-items: flex-end;
  margin-bottom: 15px;
  max-width: 100%;
  background: transparent !important;
  border: none !important;
  padding: 0 !important;
}

.message-item.sent {
  justify-content: flex-end;
}

.message-item.received {
  justify-content: flex-start;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  object-fit: cover;
}

/* 气泡样式，类似微信 */
.bubble {
  max-width: 70%;
  padding: 10px 12px;
  border-radius: 8px;
  background-color: #ffffff;
  border: 1px solid #d9d9d9;
  box-sizing: border-box;
  word-break: break-word; /* 长字串自动断行 */
  overflow-wrap: anywhere; /* 无空格也可断行 */
  flex: 0 1 auto; /* 允许收缩，避免溢出 */
}

.message-item.sent .bubble {
  background-color: #e6f7ff;
  border-color: #bae7ff;
}

.name {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.message-content {
  font-size: 14px;
  line-height: 1.5;
  color: #333;
  white-space: pre-wrap; /* 保留换行 */
  word-break: break-word; /* 长单词断行 */
  overflow-wrap: anywhere; /* 无空格也断行 */
}

.emoji-content {
  font-size: 32px;
  line-height: 1.2;
}

.file-content {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
  border: 1px solid #e0e0e0;
}

.file-content:hover {
  background-color: #eeeeee;
}

.file-icon {
  font-size: 24px;
  flex-shrink: 0;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-size {
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.file-action {
  font-size: 18px;
  flex-shrink: 0;
}

.image-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: transform 0.2s;
}

.image-content:hover {
  transform: scale(1.02);
}

.preview-image {
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.image-name {
  margin-top: 4px;
  font-size: 12px;
  color: #666;
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.message-time {
  font-size: 11px;
  color: #999;
  text-align: right;
  margin-top: 5px;
}

.input-section-wrapper {
  position: relative;
}

.input-toolbar {
  display: flex;
  gap: 8px;
  margin-bottom: 5px;
  padding-left: 2px;
}

.tool-button {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.tool-button:hover {
  background-color: #f0f0f0;
}

.emoji-panel {
  position: absolute;
  bottom: 100%;
  left: 0;
  background-color: white;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 10px;
  margin-bottom: 5px;
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 5px;
  max-height: 200px;
  overflow-y: auto;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.emoji-item {
  text-align: center;
  padding: 8px;
  font-size: 20px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.emoji-item:hover {
  background-color: #f0f0f0;
}

.input-section {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
  padding: 10px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.5;
  resize: vertical;
  min-height: 60px;
  max-height: 120px;
  font-family: inherit;
}

.message-input:focus {
  outline: none;
  border-color: #40a9ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.send-btn {
  background-color: #52c41a;
  color: white;
  min-height: 40px;
}

.send-btn:hover:not(:disabled) {
  background-color: #73d13d;
}

.send-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

/* 滚动条样式 */
.message-container::-webkit-scrollbar {
  width: 6px;
}

.message-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.message-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.message-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.user-list::-webkit-scrollbar {
  width: 6px;
}

.user-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}
</style>